package com.example.rabbitmq.demo1_delay;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Objects;

/**
 * @Author songyahui
 * @Date 2023/7/12 8:40
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg/{message}")
    public String sendMsg(@PathVariable String message){
        log.info("当前时间：{}发送一条消息{}给两个队列", new Date(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自TTL为10s队列QA："+message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自TTL为40s队列QB："+message);
        return "发送成功";
    }

    @GetMapping("/sendExpirationMsg/{message}/{ttl}")
    public String sendMsg(@PathVariable("message") String message, @PathVariable("ttl") Integer ttl){
        //设置延迟时间expiration
        rabbitTemplate.convertAndSend("X", "XC", "消息来自TTL为10s队列QA："+message, msg-> fillingTtl(msg, ttl));
        return "发送成功";
    }

    private Message fillingTtl(Message message, Integer ttl){
        if(Objects.isNull(ttl)){
            ttl = 10000;
        }
        message.getMessageProperties().setExpiration(String.valueOf(ttl));
        return message;
    }
}

